package com.sanjishu.enterlab.electricity.sale.service;

import com.sanjishu.enterlab.electricity.sale.domain.ContractFile;
import com.sanjishu.enterlab.electricity.sale.mapper.ContractFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

@Service
public class ContractFileService {

    @Value("${path.root}")
    private String rootPath;
    @Value("${path.prefix.pdf}")
    private String pdfPath;

    @Autowired
    private ContractFileMapper contractFileMapper;

    public List<ContractFile> getByContractId(Integer contractInfoId) {
        return contractFileMapper.getByContractId(contractInfoId);
    }

    public void deleteFile(Integer fileId) {
        contractFileMapper.deleteByPrimaryKey(fileId);
    }

    public void fileUpload(@RequestParam("file") MultipartFile file,
                           String name, Integer contractInfoId) throws Exception {
        String path = pdfPath+System.currentTimeMillis()+file.getOriginalFilename();
        File newFile = new File(rootPath+path);
        file.transferTo(newFile);
        ContractFile contractFile = new ContractFile();
        contractFile.setContractInfoId(contractInfoId);
        contractFile.setFileUrl(path);
        contractFile.setName(name);
        contractFileMapper.insert(contractFile);
    }
}
